module(..., package.seeall) -- seeall is insecure, but we trust us

-- flat distribution

function random(...)
	for i,mt in opairs( trax(...) ) do
		local pv = math.random() * 2 - 1
		reaper.MediaTrackInfo.SetPan(mt, pv)
	end
end

-- left-to-right equal spacing

function even(...)
	local trt = trax(...)

	if #trt == 1 then
		local mt = unpack(trt)	-- get first and only element
		reaper.MediaTrackInfo.SetPan(mt, 0)
	else
		local interval = 2/(#trt-1)
		for i,mt in opairs(trt) do
			local pv = (i-1) * interval - 1
			reaper.MediaTrackInfo.SetPan(mt, pv)
		end
	end
end

-- other distributions can be programmed easily:

function crowd(...)
	-- roll twelve to approximate Gaussian:
	local function gauss12()
	  local sum = 0.0
	  for i = 1,12 do
		sum = sum + math.random()
	  end
	  return( (sum - 6.0) / 6.0 )
	end

	for i,mt in opairs( trax(...) ) do
		local pan = gauss12()
		reaper.MediaTrackInfo.SetPan(mt, pan)
	end
end

--  or not so easily

function spread(...)
	local trt = trax(...)

	if #trt == 1 then
		local mt = unpack(trt)	-- get first and only element
		reaper.MediaTrackInfo.SetPan(mt, 0)
	else
		local interval = math.pow( 2, 1/(#trt-1) )	-- root of two
		local mp = math.floor(#trt/2)
		for i = 1,mp do
			local pan = math.pow( interval, #trt - i ) - 1
			reaper.MediaTrackInfo.SetPan( trt[ i ], -pan)
			reaper.MediaTrackInfo.SetPan( trt[ #trt - i + 1 ], pan)
		end
		if math.mod( #trt, 2 ) == 1 then
			reaper.MediaTrackInfo.SetPan( trt[ mp+1 ], 0)
		end
	end
end

